import React, {Fragment}from "react";
import {queryWebUser, queryWebRole, addWebUser, updateWebRole, delWebUser} from "../../../service/api";
import {Table, Button, Modal, Form, Input, Popconfirm, Checkbox, Badge, message, Select} from 'antd';
import TableLayout from '../../../Layout/TableLayout';
const FormItem = Form.Item;
const Option = Select.Option;
let columnsRoot = [];
import md5 from 'blueimp-md5';
import './WebUser.less'

class AddWebUser extends React.Component {
    state = {
        visible: false,
        confirmLoading: false,
        role: []
    }
    showModal = () => {
        let self = this;
        this.setState({
            visible: true,
        },function () {
            queryWebRole().then(function (data) {
                if(data.code === 200){
                    self.setState({
                        role: data.data,
                    })

                }
            })
        });
    }
    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                let formInfo = values;
                formInfo.roleIds = [Number(values.roleIds)]
                values.password = md5(values.password)
                addWebUser(formInfo).then(function (data) {
                    if(data.code === 200){
                        self.props.retrieve();
                        self.setState({
                            visible: false,
                            confirmLoading: false,
                        })
                        self.props.form.resetFields();
                        self.props.close();
                    }else{
                        message.error(data.msg)
                        self.setState({
                            confirmLoading: false
                        })
                    }
                })

            }
        });

    }
    handleCancel = () => {
        this.props.close();
        this.setState({
            visible: false,
            confirmLoading: false
        });
        this.props.form.resetFields();
    }
    render() {
        const { visible, confirmLoading } = this.state;
        const { getFieldDecorator } = this.props.form;

        let dropDownList = <FormItem>{getFieldDecorator('roleIds',
            {
                rules: [{ required: true, message: '请选择角色' }],
            })(
            <Select style={{width: 150}} placeholder="选择角色">
                { this.state.role.length ? this.state.role.map((item, idx) => (
                    <Option key={idx} value={`${item.roleId}`}>{item.roleName}</Option>
                )) : <Option value=''>选择角色</Option> }
            </Select>
        )}</FormItem>

        return (
            <Fragment>
                <Button type="primary" className="fl" onClick={this.showModal}>新增用户</Button>
                <Modal title="新增用户"
                       visible={visible}
                       maskClosable={false}
                       onOk={this.handleOk}
                       confirmLoading={confirmLoading}
                       onCancel={this.handleCancel}
                       okText="确定"
                       cancelText="取消"
                >

                    <Form className="modalForm">
                        <FormItem>
                            {getFieldDecorator('username', {
                                rules: [{ required: true, message: '请填写正确的用户名!',max: 12, min: 2 }],
                            })(
                                <Input placeholder="用户名(长度2-12)" />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('password', {
                                rules: [{ required: true, message: '请输入正确的密码!',max: 12, min: 6 }],
                            })(
                                <Input type="password" placeholder="密码(长度6-12)" />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('mobile', {
                                rules: [{ required: true, message: '请填写正确的手机号!',len: 11 }],
                            })(
                                <Input placeholder="手机号" />
                            )}
                        </FormItem>
                        {dropDownList}
                        <FormItem>
                            {getFieldDecorator('status', {
                                valuePropName: 'checked',
                                initialValue: true,
                            })(
                                <Checkbox>启用</Checkbox>
                            )}
                        </FormItem>
                    </Form>

                </Modal>
            </Fragment>
        );
    }
}

const AddWebUserForm = Form.create()(AddWebUser);

class ModWebUser extends React.Component {
    state = {
        visible: false,
        confirmLoading: false,
        role: [],
        info:[],
        town: this.props.town
    }

    componentWillReceiveProps(nextProps) {
        let self = this;
        if(nextProps.visible && nextProps.modId){
            queryWebRole().then(function (data) {
                if(data.code === 200){
                    self.setState({
                        role: data.data,
                    })

                }
            })
            self.setState({visible: nextProps.visible, info: nextProps.info, modId: nextProps.modId})
        }
    }

    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });

                let modInfo = values;
                modInfo.roleIds = [Number(values.roleIds.key)];
                values.pass = md5(values.pass)
                updateWebRole(self.state.modId, modInfo).then(function (data) {
                    if(data.code === 200){
                        self.props.retrieve();
                        self.setState({
                            visible: false,
                            confirmLoading: false
                        })
                        self.props.close();
                        self.props.form.resetFields();
                    }else{
                        message.error(data.msg)
                        self.setState({
                            confirmLoading: false
                        })
                    }

                })
        
            }
        });

    }
    handleCancel = () => {
        this.props.close();
        this.setState({
            visible: false,
            confirmLoading: false
        });
        this.props.form.resetFields();
    }
    render() {
        const { visible, confirmLoading } = this.state;
        const { getFieldDecorator } = this.props.form;
        let nowVal, nowRole;
        if(Object.keys(this.state.info).length){
            nowVal = this.state.info.roleIds[0];
            nowRole = this.state.info.roles[0];
        }

        let dropDownList = <FormItem>{getFieldDecorator('roleIds',
            {
                rules: [{ required: true, message: '请选择角色' }],
                initialValue: {key: nowVal, label: nowRole}
            })(
            <Select style={{width: 150}} placeholder="选择角色" labelInValue>
                { this.state.role.length ? this.state.role.map((item, idx) => (
                    <Option key={idx} value={`${item.roleId}`}>{item.roleName}</Option>
                )) : <Option value=''>选择角色</Option> }
            </Select>
        )}</FormItem>

        return (
                <Modal title="修改用户"
                       visible={visible}
                       maskClosable={false}
                       onOk={this.handleOk}
                       confirmLoading={confirmLoading}
                       onCancel={this.handleCancel}
                       okText="确定"
                       cancelText="取消"
                >

                    {visible && <Form className="modalForm">

                        <FormItem>
                            {getFieldDecorator('pass', {
                                rules: [{ required: true, message: '请输入正确的密码!',max: 12, min: 6 }],
                            })(
                                <Input type="password" placeholder="需要时修改密码(长度6-12)" />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('mobile', {
                                rules: [{ message: '请填写正确的手机号!',len: 11 }],
                                initialValue: this.state.info.mobile
                            })(
                                <Input placeholder="手机号" />
                            )}
                        </FormItem>
                        {dropDownList}
                        <FormItem>
                            {getFieldDecorator('status', {
                                valuePropName: 'checked',
                                initialValue: this.state.info.status,
                            })(
                                <Checkbox>启用</Checkbox>
                            )}
                        </FormItem>
                    </Form>}

                </Modal>
        );
    }
}

const ModWebUserForm = Form.create()(ModWebUser);

class WebUser extends React.Component{

    state = {
        permissions: JSON.parse(localStorage.permissions),
        data: [],
        showData: [],
        modVisible: false,
        town: []
    }

    componentDidMount() {
        this.getData();
    }

    getData = () => {
        let self = this;
        self.setState({loading: true})
        queryWebUser().then(function (data) {
            if(data.code === 200){
                self.setState({data: data.data, showData: data.data, loading: false, modVisible:false})
            }
        })


    }

    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((err, values) => {
            if (!err) {
                let value = values.userName.replace(/^\s+|\s+$/g,""), data = []
                for(let i in this.state.data){
                    if(this.state.data[i].username.indexOf(value) > -1){
                        data.push(this.state.data[i])
                    }
                }
                this.setState({showData: data})
            }
        });
    }
    turnModalDown = () => {
        this.setState({modVisible: false})
    }

    mod = (id, key) => {
        this.setState({modId :id, modVisible: true, modKey: key});
    }

    del = (id) => {
        let self = this;
        delWebUser(id).then(function (data) {
            if(JSON.parse(data).code === 200){
                self.getData();
            }

        })
    }

    render(){
        const { getFieldDecorator } = this.props.form;
        let data = [];
        if(this.state.showData.length){
            for(let i in this.state.showData){
                data.push({
                    key: i,
                    userId: this.state.showData[i].userId,
                    username: this.state.showData[i].username,
                    loginip: this.state.showData[i].loginip,
                    mobile: this.state.showData[i].mobile,
                    roles: this.state.showData[i].roles,
                    status: this.state.data[i].status > 0?<Fragment><Badge status="success" />启用</Fragment>:<Fragment><Badge status="error" />停用</Fragment>

                })
            }
        }

        columnsRoot = [
            {
                dataIndex: 'userId',
                title: 'id'
            },
            {
                dataIndex: 'username',
                title: '用户名'
            },
            {
                dataIndex: 'loginip',
                title: '登录IP'
            },
            {
                dataIndex: 'mobile',
                title: '联系电话'
            },
            {
                dataIndex: 'roles',
                title: '所属角色'
            },
            {
                dataIndex: 'status',
                title: '状态'
            },
            {
                title: '操作',
                width: 250,
                render: (record) => (
                    <div className="tableOperation">
                        {this.state.permissions["sys:user:update"]?<Button type="primary" id={record.userId} onClick={ () => this.mod(record.userId,record.key)}>修改</Button>:true}
                        {this.state.permissions["sys:user:delete"]?
                            <Popconfirm placement="leftBottom" title={`确定删除用户:${record.username}吗?`} id={record.userId.toString()} onConfirm={() => this.del(record.userId)} okText="确定" cancelText="取消">
                                <Button type="danger" id={record.userId} ghost>删除</Button>
                            </Popconfirm>:true}
                    </div>
                )
            }
        ]


        return(
            <TableLayout title="平台用户管理">
                <div className="webUser">
                    <div className="clearfix">
                        {this.state.permissions["sys:user:add"]?<AddWebUserForm retrieve={this.getData} close={this.turnModalDown} town={this.state.town} />:true}
                        <ModWebUserForm visible={this.state.modVisible} modId={this.state.modId} close={this.turnModalDown} info={this.state.showData[this.state.modKey]} retrieve={this.getData} />
                        <Form className="searchForm fr" layout="inline" onSubmit={this.handleSubmit}>
                            <FormItem>
                                {getFieldDecorator('userName',{
                                    initialValue: ""
                                })(
                                    <Input placeholder="用户名称" />
                                )}
                            </FormItem>

                            <FormItem>
                                <Button
                                    type="primary"
                                    htmlType="submit"
                                >
                                    搜索
                                </Button>
                            </FormItem>
                        </Form>
                    </div>

                    <Table className="mt10" columns={columnsRoot} dataSource={data} loading={this.state.loading} bordered />
                </div>
            </TableLayout>
        )
    }
}
const WebUsertForm = Form.create()(WebUser);
export default WebUsertForm;